package com.lib.framework.receiver

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import com.lib.framework.base.BaseBroadcastReceiver
import com.lib.framework.manager.thread.bgThreadRun


/**
 * 网络连接 广播接收器
 * @author keanbin
 */
abstract class ANetworkConnectivityBroadcastReceiver(context: Context) : BaseBroadcastReceiver(context) {

    override fun getIntentFilter(): IntentFilter {
        val intentFilter = IntentFilter()
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        return intentFilter
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) return

        when (intent.action) {
            ConnectivityManager.CONNECTIVITY_ACTION -> {
                bgThreadRun {
                    val manager = mContext
                            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                    val activeNetwork = manager.activeNetworkInfo
                    val isConnected = activeNetwork?.isConnected ?: false
                    onConnectivityChange(isConnected)
                }
            }
        }
    }

    /**
     * 网络连接 发生改变
     */
    abstract fun onConnectivityChange(isConnected: Boolean)
}